set more off

use dataset, clear

*** covariates ***

local controls dfederalaidpcp dstateaidpcp lpopulation pct_white pct_senior pct_renter lmedianincome 
local economy davgannualwage demployment dunemployment propvaluechange

local X `economy' `controls'

su demvoteshare, det
replace demvoteshare = (demvoteshare - r(min))/(r(max)-r(min))

gen presyear = !mi(demvoteshare)

keep if !mi(overridep)

tabulate year, gen(year_)

local y override

gen label = ""
gen B = ""
gen SE = ""
gen P = ""
gen outcome = .
gen years = .
local i = 1
local j = 1
foreach y in override overridep {
	foreach years in 0 1 {
		local years = `years' + 1
		foreach x in `X' {
			local templabel : var label `x'
			replace label = "`templabel'" if _n == `i'
			reg `x' `y' i.year [aw=population] if presyear == `years' - 1, cl(town)
			replace B = string(_b[`y'], "%20.02fc") if _n == `i'
			replace SE = string(_se[`y'], "%20.02fc") if _n == `i'
			replace P = string(2*(1-normal(_b[`y']/_se[`y'])), "%20.02fc") if _n == `i'
			replace outcome = `j' if _n == `i'
			replace years = `years' if _n == `i'
			local i = `i' + 1
		}
	}
	local j = `j' + 1
}

replace SE = "(" + SE + ")"
replace B = B + "*" if real(P) < .05
replace B = B + "*" if real(P) < .01
replace B = B + "*" if real(P) < .001

keep if !mi(B)

bys outcome: gen index = _n

keep index label outcome B SE years

reshape i index
reshape j outcome 1 2
reshape xij B SE
reshape xi label years
reshape wide

l

drop index
bys years: gen index = _n
reshape i index
reshape j years
reshape xij B1 SE1 B2 SE2
reshape xi label

reshape wide

l

expand 3

sort index

bys index: gen index2 = _n

foreach x in 11 21 12 22 {
replace B`x' = SE`x' if index2 == 2
replace B`x' = "" if index2 == 3
}
replace label = "" if index2 != 1

order label B11 B12 B21 B22

keep if _n < 33

#delimit;

listtex label B11 B21 B12 B22
	using "table A3.tex"
	,
	replace
	type rstyle(tabular)
	head(
		"\begin{tabular*}{\hsize}{@{\hskip\tabcolsep\extracolsep\fill}l*{7}{c}}"
		"\toprule&(1)&(2)&(3)&(4)""\\
		Outcome:&Held referendum&Held referendum&Passed increase&Passed increase\\
		Years:&Non-presidential&Presidential&Non-presidential&Presidential\\
		
		\midrule"
	)
	foot("\bottomrule\end{tabular*}")
	;
	
#delimit cr
